package dk.itu.mobile.util;

import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;

import dk.itu.mobile.vo.Envelope;
import dk.itu.mobile.vo.Task;
import dk.itu.mobile.vo.User;


/**
 * @author jacobbj
 *Serializes/Deserializes Envelopes with state changes for jGroup communication in task-manager.
 *
 */
public class XMLSerializer extends TaskListSerializer {

	public static String getXML(String command, Object object) {

		if (object instanceof User) return MarshallEnvelope(new Envelope(command, (User)object));
		else if (object instanceof Task) return MarshallEnvelope(new Envelope(command, (Task)object));
		return null;

	}

	public static Object getObject(String xml) {

		Envelope env = unMarshallEnvelope(xml);
		
		if ( env.type.equalsIgnoreCase("userjob")) return new User(env.username, env.password);
		if ( env.type.equalsIgnoreCase("taskjob"))	
		{
			List<User> userlist = new ArrayList<User>();
			String[] users = env.attendants.split(",");
			for (String u : users) userlist.add(new User (u,""));
			return new Task(env.taskname, env.id, env.date, env.description, userlist);
		}

		return null;
	}

	public static String getCommand(String xml) {

		Envelope env = unMarshallEnvelope(xml);
		return env.command.trim();
	}

	private static Envelope unMarshallEnvelope(String xml) {

		JAXBContext jaxbContext;

		Envelope anEnvelope = null;
		StringReader stream = new StringReader(xml);

		try {

			jaxbContext = JAXBContext.newInstance(Envelope.class);

			// deserialize  XML into java objects.
			anEnvelope = (Envelope)jaxbContext.createUnmarshaller().unmarshal(stream);

		} catch (JAXBException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return anEnvelope;
	}


	private static String MarshallEnvelope(Envelope env) {

		StringWriter writer = new StringWriter();

		try {
			JAXBContext jaxbContext = JAXBContext.newInstance(Envelope.class);
			jaxbContext.createMarshaller().marshal(env, writer);
		} catch (JAXBException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return (writer.toString());

	}
}
